package com.faxe.educar.ws.daohibernate;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.faxe.educar.ws.dao.ServiceDAO;
import com.faxe.educar.ws.to.ServiceTO;
import com.faxe.educar.ws.to.UserTO;

@Repository("serviceDAOHibernate")
public class ServiceDAOHibernate extends GenericDAOHibernate<ServiceTO> implements ServiceDAO {

	public List<ServiceTO> getList() {
		String sqlStr = "SELECT * FROM services";
		
		List<ServiceTO> services = (List<ServiceTO>) getSession().createSQLQuery(sqlStr).list();
		
		return services;
	}

	public List<ServiceTO> getFilterList(String category, String subcategory,
			String state, String city, String query) {
		
		String sqlStr;
		Boolean flag = true;
		
		sqlStr = "SELECT * FROM services";
		
		if (category != null && !category.equals(""))
		{
			sqlStr += " WHERE category LIKE '%"+category+"%'";
			flag = false;
		}
		if (subcategory != null && !"".equals(subcategory)){
			if (flag){
				sqlStr += " WHERE ";
			}else{
				sqlStr += " AND ";
			}
			sqlStr += "subcategory LIKE '%"+subcategory+"%'";
			flag = false;
		}
		if (city != null && !"".equals(city)){
			if (flag){
				sqlStr += " WHERE ";
			}else{
				sqlStr += " AND ";
			}
			sqlStr += "city LIKE '%"+city+"%'";
			flag = false;
		}
		if (state != null && !"".equals(state)){
			if (flag){
				sqlStr += " WHERE ";
			}else{
				sqlStr += " AND ";
			}
			sqlStr += "state LIKE '%"+state+"%'";
			flag = false;
		}
		if (query != null && !"".equals(query)){
			String[] splitQuery = query.split(" ");
			for (String str : splitQuery){
				if (flag){
					sqlStr += " WHERE title LIKE '%"+str+"%' OR CATEGORY LIKE '%"+str+"%' OR SUBCATEGORY LIKE '%"+str+"%'";
					flag = false;
				}else {
					sqlStr += " OR title LIKE '%"+str+"%' OR CATEGORY LIKE '%"+str+"%' OR SUBCATEGORY LIKE '%"+str+"%'";
				}
			}
		}
		List<ServiceTO> services = getSession().createSQLQuery(sqlStr).addEntity(ServiceTO.class).list();
		return services;
	}
}
